#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    int getnum(ListNode* h)
    {
        if (!h)return 0;
        ListNode* cur = h;
        int num = 0;
        while (cur)cur = cur->next, num++;
        return num;
    }
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        if (!headA || !headB)return nullptr;
        int n1 = getnum(headA);
        int n2 = getnum(headB);
        ListNode* cur1 = headA;
        ListNode* cur2 = headB;
        while (n1 > n2)
        {
            cur1 = cur1->next;
            n1--;
        }
        while (n2 > n1)
        {
            cur2 = cur2->next;
            n2--;
        }

        while (cur1 && cur2)
        {
            if (cur1 == cur2)return cur1;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        return nullptr;
    }
};